/**
 *
 */
package com.ybkj.daijia.api.driver.v4;

import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.Error;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.Config;
import com.ybkj.daijia.server.errand.ErrandOrderTypeOtherServices;
import com.ybkj.daijia.server.errand.ErrandOrderTypeTips;
import com.ybkj.daijia.server.errand.OrderMemo;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.OrderAcceptEvent;
import com.ybkj.daijia.server.event.model.OrderFillV2Event;
import com.ybkj.daijia.server.event.model.OrderRecordEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.mc.PassengerGrade;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.AreaOfEmploy;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.FinancialRecord;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.Order.OrderCarTypeDetail;
import com.ybkj.daijia.server.model.OrderGroup;
import com.ybkj.daijia.server.model.WeixinManager;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.service.AreaOfEmployService;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FinancialRecordService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderGroupService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.OrderStatusService;
import com.ybkj.daijia.server.service.WeixinManagerService;
import com.ybkj.daijia.server.service.WeixinManagerXOrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuanxian.Line;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author bo
 *
 */
@Controller("ProcessControllerV4")
@RequestMapping(value = "driver/api/rest/v4")
public class ProcessController {

    private static final Logger logger = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private DriverService driverService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderStatusService orderStatusService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private FinancialRecordService financialRecordService;

    @Autowired
    private DriverLoginService driverLoginService;

    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private ZhuanxianService zhuanxianService;

    @Autowired
    private FreightService freightService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;

    @Autowired
    private OrderGroupService orderGroupService;

    @Autowired
    private AreaOfEmployService areaOfEmployService;

    @Autowired
    private WeixinManagerXOrderService weixinManagerXOrderService;

    @Autowired
    private WeixinManagerService weixinManagerService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    public static void main(String[] args) {
        Calendar nowCalendar = Calendar.getInstance();
        int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);
        //查询今日
        Calendar calendaer = Calendar.getInstance();
        calendaer.set(Calendar.HOUR_OF_DAY, 0);
        calendaer.set(Calendar.MINUTE, 0);
        calendaer.set(Calendar.SECOND, 0);
        Date end = calendaer.getTime();
        Date begin = DateUtils.addHours(end, -24);
        if (0 <= nowHour) {
            end = DateUtils.addHours(end, 24);
            begin = DateUtils.addHours(begin, 24);
        }
        System.out.println("end = " + end + "  bengin =" + begin);
    }

    /**
     * 司机获取附近司机
     * @param longitude 经度
     * @param latitude 纬度
     * @param appKey
     * @param token token令牌
     * @param timestamp 时间戳
     * @return
     */
    @RequestMapping(value = "queryNearDrivers", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryNearDrivers(String employToken, Double longitude, Double latitude) {

        logger.debug("recv employToken:{},longitude:{},latitude:{}", employToken, longitude,
            latitude);

        if (StringUtils.isBlank(employToken) || null == longitude || null == latitude) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {
            Setting setting = settingUtils.get();

            List<Driver> drivers = driverService
                .queryNearDrivers2(driver.getId(), longitude, latitude);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(drivers)) {
                for (Driver d : drivers) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("driverName", d.getName());
                    map.put("driverHead", setting.getWebUrl() + "/upload/driver/" + d.getPhoto());
                    map.put("driverDistance", d.getDistanceStr());
                    map.put("driverMeter", d.getDistance() * 1000);
                    if (d.getStatus().equals(Driver.DRIVER_ONLINE)) {
                        map.put("driverStatus", 0);
                    } else {
                        map.put("driverStatus", 1);
                    }
                    map.put("driverLng", d.getLongitude());
                    map.put("driverLat", d.getLatitude());
                    map.put("workCar", d.isWorkCar());
                    mapList.add(map);
                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 queryNearDrivers error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "indexPayments", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport indexPayments(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Setting setting = settingUtils.get();

            Map<String, Object> dataMap = new HashMap<String, Object>();

            //统计
            Calendar nowCalendar = Calendar.getInstance();
            int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);

            //查询今日
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date end = calendaer.getTime();
            Date begin = DateUtils.addHours(end, -24);
            if (setting.getWorkBegin() <= nowHour) {
                end = DateUtils.addHours(end, 24);
                begin = DateUtils.addHours(begin, 24);
            }

            List<DriverPaymentsRecord> todayRecords = driverPaymentsRecordService
                .listIndexPayments(driver.getId(), begin, end);
            List<Map<String, Object>> todayRecordsMap = new ArrayList<Map<String, Object>>();
            BigDecimal todayTotal = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(todayRecords)) {
                for (DriverPaymentsRecord driverPaymentsRecord : todayRecords) {
                    todayTotal = todayTotal.add(driverPaymentsRecord.getMoney());

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("happend", driverPaymentsRecord.getHappend().getTime());
                    map.put("orderType", driverPaymentsRecord.getOrderType());
                    map.put("money", driverPaymentsRecord.getMoney());
                    todayRecordsMap.add(map);
                }
            }
            dataMap.put("todayTotal", todayTotal);
            dataMap.put("todayRecords", todayRecordsMap);

            //查询昨日
            begin = DateUtils.addHours(begin, -24);
            end = DateUtils.addHours(end, -24);

            List<DriverPaymentsRecord> yesterdayRecords = driverPaymentsRecordService
                .listIndexPayments(driver.getId(), begin, end);
            List<Map<String, Object>> yesterdayRecordsMap = new ArrayList<Map<String, Object>>();
            BigDecimal yesterdayTotal = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(yesterdayRecords)) {
                for (DriverPaymentsRecord driverPaymentsRecord : yesterdayRecords) {
                    yesterdayTotal = yesterdayTotal.add(driverPaymentsRecord.getMoney());

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("happend", driverPaymentsRecord.getHappend().getTime());
                    map.put("orderType", driverPaymentsRecord.getOrderType());
                    map.put("money", driverPaymentsRecord.getMoney());
                    yesterdayRecordsMap.add(map);
                }
            }
            dataMap.put("yesterdayTotal", yesterdayTotal);
            dataMap.put("yesterdayRecords", yesterdayRecordsMap);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(dataMap);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver indexPayments error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "indexOrders")
    public @ResponseBody
    ResultTransport indexOrders(String employToken) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Map<String, Object> dataMap = new HashMap<String, Object>();

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            //新工单
            if (serviceSetting.isDaijia()) {
                List<Order> daijiaOrders = new ArrayList<Order>();
                List<Map<String, Object>> daijiaOrdersMap = new ArrayList<Map<String, Object>>();

                List<Order> newOrders = orderService
                    .findByDriverAndStatus(driver, Order.ORDER_STATUS_YIPAIDAN);
                if (CollectionUtils.isNotEmpty(newOrders)) {
                    daijiaOrders.addAll(newOrders);
                }

                List<Order> busyOrders = orderService
                    .findByDriverAndStatus(driver, Order.ORDER_STATUS_BUSY);
                if (CollectionUtils.isNotEmpty(busyOrders)) {
                    daijiaOrders.addAll(busyOrders);
                }

                if (CollectionUtils.isNotEmpty(daijiaOrders)) {
                    for (Order order : daijiaOrders) {
                        Company thisCompany = companyService.findOne(order.getCompanyId());
                        if (null != thisCompany) {
                            Area area = null;
                            //客户经理单独收费
                            if (null != order.getManagerId()) {
                                WeixinManager weixinManager = weixinManagerService
                                    .findOne(order.getManagerId());
                                if (null != weixinManager && null != weixinManager.getAreaId()) {
                                    area = areaService.findOneWithCharge(weixinManager.getAreaId());
                                }
                            }
                            //客户等级单独收费
                            if (null == area) {
                                Passenger passenger = memberService
                                    .findOnePassenger(order.getClientId());
                                if (null != passenger) {
                                    if (null != passenger.getGrade_id()) {
                                        PassengerGrade passengerGrade = memberService
                                            .findOneGrade(passenger.getGrade_id());
                                        if (null != passengerGrade) {
                                            if (null != passengerGrade.getDaijiaAreaId()) {
                                                area = areaService.findOneWithCharge(
                                                    passengerGrade.getDaijiaAreaId());
                                            }
                                        }
                                    }
                                    if (null == area) {
                                        area = areaService
                                            .findOneWithCharge(thisCompany.getAreaId());
                                    }
                                } else {
                                    area = areaService.findOneWithCharge(thisCompany.getAreaId());
                                }
                            }

                            if (null == area) {
                                area = areaService.findOneWithCharge(thisCompany.getAreaId());
                            }

                            Map<String, Object> daijiaMap = new HashMap<String, Object>();
                            daijiaMap.put("orderId", order.getId());
                            daijiaMap.put("orderNumber", order.getOrderNumber());
                            daijiaMap.put("time", order.getServerTime().getTime());
                            if (null != order.getStartDriveDate()) {
                                daijiaMap.put("status", 4);
                            } else if (null != order.getArrivePlaceDate()) {
                                daijiaMap.put("status", 3);
                            } else {
                                daijiaMap.put("status", order.getStatus());
                            }

                            daijiaMap.put("treatment", order.isTreatment());
                            if (order.isTreatment()) {
                                daijiaMap.put("realCash", order.getRealCash());
                                daijiaMap.put("guoluMoney", order.getGuoluMoney());
                                daijiaMap.put("yuanchengMoney", order.getYuanchengMoney());
                                daijiaMap.put("otherMoney", order.getOtherMoney());
                                daijiaMap.put("couponMoney", order.getCouponMoney());
                                daijiaMap.put("mileage", order.getMileage());
                                daijiaMap.put("waitedTime", order.getWaitedTime());
                                daijiaMap.put("travelTime", order.getTravelTime());
                                daijiaMap.put("startPrice", order.getStartPrice());
                                daijiaMap.put("mileagePrice", order.getMileagePrice());
                                daijiaMap.put("waitPrice", order.getWaitedPrice());
                                daijiaMap.put("runTimePrice", order.getTravelPrice());
                            }

                            daijiaMap.put("orderType", "daijia");
                            daijiaMap.put("startLng", order.getClientLongitude());
                            daijiaMap.put("startLat", order.getClientLatitude());
                            daijiaMap.put("endLng", order.getToPlaceLongitude());
                            daijiaMap.put("endLat", order.getToPlaceLatitude());
                            daijiaMap.put("fromPlace", order.getFromPlace());
                            daijiaMap.put("toPlace", order.getToPlace());
                            daijiaMap.put("passengerPhone", order.getUserPhone());
                            daijiaMap.put("passengerName", order.getClientName());
                            daijiaMap.put("companyAbbreviation", thisCompany.getAbbreviation());
                            daijiaMap.put("memo", order.getMemo());
                            if (order.isFixPrice()) {
                                daijiaMap.put("fixPrice", true);
                            } else {
                                daijiaMap.put("fixPrice", false);
                            }
                            daijiaMap.put("shouldCash", order.getShouldCash());

                            boolean hasAreaOfEmploy = false;
                            if (null != order.getAreaOfEmployId()) {
                                AreaOfEmploy areaOfEmploy = areaOfEmployService
                                    .findOneWithCharge(order.getAreaOfEmployId());
                                if (null != areaOfEmploy) {
                                    daijiaMap.put("chargeStartTimes",
                                        areaOfEmploy.getChargeStartTimes());
                                    hasAreaOfEmploy = true;
                                }
                            }
                            if (!hasAreaOfEmploy) {
                                daijiaMap.put("chargeStartTimes", area.getChargeStartTimes());
                            }

                            daijiaOrdersMap.add(daijiaMap);
                        }
                    }
                }
                dataMap.put("daijiaTasks", daijiaOrdersMap);
            }

            if (serviceSetting.isZhuanche()) {
                //----专车----
                List<com.ybkj.daijia.server.zhuan.Order> zhuancheOrders = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();
                List<Map<String, Object>> zhuancheOrdersMap = new ArrayList<Map<String, Object>>();

                List<com.ybkj.daijia.server.zhuan.Order> newOrders_zhuan = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();
                newOrders_zhuan = zhuancheService.queryByEmployId(driver.getId(), "pai");//1
                if (CollectionUtils.isNotEmpty(newOrders_zhuan)) {
                    zhuancheOrders.addAll(newOrders_zhuan);
                }

                List<com.ybkj.daijia.server.zhuan.Order> excuteTasks_zhuan = new ArrayList<com.ybkj.daijia.server.zhuan.Order>();
                excuteTasks_zhuan = zhuancheService
                    .queryByEmployId(driver.getId(), "waitorrun");//2,3,4,5
                if (CollectionUtils.isNotEmpty(excuteTasks_zhuan)) {
                    zhuancheOrders.addAll(excuteTasks_zhuan);
                }

                if (CollectionUtils.isNotEmpty(zhuancheOrders)) {
                    for (com.ybkj.daijia.server.zhuan.Order order : zhuancheOrders) {
                        Map<String, Object> zhuancheMap = new HashMap<String, Object>();
                        zhuancheMap.put("orderId", order.getId());
                        zhuancheMap.put("orderNumber", order.getOrderNo());
                        zhuancheMap.put("time", order.getServerTime().getTime());
                        zhuancheMap.put("status", order.getStatus());

                        zhuancheMap.put("treatment", order.isTreatment());
                        if (order.isTreatment()) {
                            zhuancheMap.put("realCash", order.getRealPay());
                            zhuancheMap.put("guoluMoney", order.getGuoluMoney());
                            zhuancheMap.put("yuanchengMoney", order.getYuanchengMoney());
                            zhuancheMap.put("otherMoney", order.getOtherMoney());
                            zhuancheMap.put("couponMoney", order.getCouponMoney());
                            zhuancheMap.put("mileage", order.getMileage());
                            zhuancheMap.put("waitedTime", order.getMidwayWait());
                            zhuancheMap.put("travelTime", order.getRunTime());
                            zhuancheMap.put("startPrice", order.getStartPrice());
                            zhuancheMap.put("mileagePrice", order.getMileagePrice());
                            zhuancheMap.put("waitPrice", order.getWaitPrice());
                            zhuancheMap.put("runTimePrice", order.getRunTimePrice());
                        }

                        zhuancheMap.put("orderType", "zhuanche");
                        zhuancheMap.put("serviceType", order.getServiceType());
                        if (null != order.getServiceType()) {
                            if (order.getServiceType()
                                .equals(com.ybkj.daijia.server.zhuan.Order.ServiceType.jieji)
                                || order.getServiceType()
                                .equals(com.ybkj.daijia.server.zhuan.Order.ServiceType.songji)) {
                                zhuancheMap.put("flightNo", order.getFlightNo());
                            } else if (order.getServiceType()
                                .equals(com.ybkj.daijia.server.zhuan.Order.ServiceType.jiezhan)
                                || order.getServiceType()
                                .equals(com.ybkj.daijia.server.zhuan.Order.ServiceType.songzhan)) {
                                zhuancheMap.put("trainNo", order.getTrainNo());
                            }
                        }
                        zhuancheMap.put("startLng", order.getStartLng());
                        zhuancheMap.put("startLat", order.getStartLat());
                        zhuancheMap.put("endLng", order.getEndLng());
                        zhuancheMap.put("endLat", order.getEndLat());
                        zhuancheMap.put("fromPlace", order.getStartAddress());
                        zhuancheMap.put("toPlace", order.getEndAddress());
                        zhuancheMap.put("passengerPhone",
                            order.getShowPhone() != null ? order.getShowPhone()
                                : order.getPassengerPhone());
                        zhuancheMap.put("passengerName", order.getPassengerName());
                        zhuancheMap.put("companyAbbreviation", order.getCompanyName());
                        zhuancheMap.put("isMakePrice", order.getIsMakePrice());
                        zhuancheMap.put("makePrice", order.getMakePrice());
                        zhuancheMap.put("memo", order.getMemo());
                        zhuancheMap.put("carTypeName", order.getCarTypeName());
                        zhuancheMap.put("budgetPay", order.getBudgetPay());//预算金额
                        zhuancheMap.put("shouldPay", order.getRealPay());//应该支付的钱
                        zhuancheMap.put("bookStatus",
                            order.getBookStatus() != null ? order.getBookStatus() : 0);

                        if (null != order.getArea()) {
                            zhuancheMap
                                .put("chargeStartTimes", order.getArea().getChargeStartTimes());
                        } else {
                            zhuancheMap.put("chargeStartTimes", null);
                        }

                        zhuancheOrdersMap.add(zhuancheMap);
                    }
                }
                dataMap.put("zhuanTasks", zhuancheOrdersMap);
                //----专车----
            }

            if (serviceSetting.isPaotui()) {
                //----跑腿订单----
                List<com.ybkj.daijia.server.errand.Order> errandOrders = new ArrayList<com.ybkj.daijia.server.errand.Order>();
                List<Map<String, Object>> errandOrdersMap = new ArrayList<Map<String, Object>>();

                List<com.ybkj.daijia.server.errand.Order> newOrders_errand = new ArrayList<com.ybkj.daijia.server.errand.Order>();
                newOrders_errand = errandService
                    .listByEmployId(driver.getId(), "pai", driver.getLastLatitude(),
                        driver.getLongitude());
                if (CollectionUtils.isNotEmpty(newOrders_errand)) {
                    errandOrders.addAll(newOrders_errand);
                }

                List<com.ybkj.daijia.server.errand.Order> excuteTasks_errand = new ArrayList<com.ybkj.daijia.server.errand.Order>();
                excuteTasks_errand = errandService
                    .listByEmployId(driver.getId(), "waitorrun", driver.getLastLatitude(),
                        driver.getLongitude());
                if (CollectionUtils.isNotEmpty(excuteTasks_errand)) {
                    errandOrders.addAll(excuteTasks_errand);
                }

                if (CollectionUtils.isNotEmpty(errandOrders)) {
                    for (com.ybkj.daijia.server.errand.Order order : errandOrders) {
                        Map<String, Object> errandMap = new HashMap<String, Object>();
                        errandMap.put("orderId", order.getId());
                        errandMap.put("orderNumber", order.getOrderNo());
                        if (null != order.getStartTime()) {
                            errandMap.put("time", order.getStartTime().getTime());
                        } else {
                            errandMap.put("time", (new Date()).getTime());
                        }
                        errandMap.put("status", order.getStatus());

                        errandMap.put("treatment", order.getTreatment());
                        if (order.getTreatment()) {
                            errandMap.put("realCash", order.getRealPay());
                            errandMap.put("guoluMoney", order.getGuoluMoney());
                            errandMap.put("yuanchengMoney", order.getYuanchengMoney());
                            errandMap.put("otherMoney", order.getOtherMoney());
                            errandMap.put("couponMoney", order.getCouponMoney());
                            errandMap.put("mileage", order.getMileage());
                            errandMap.put("waitedTime", order.getWaitedTime());
                            errandMap.put("travelTime", order.getTravelTime());
                            errandMap.put("startPrice", order.getStartPrice());
                            errandMap.put("mileagePrice", order.getMileagePrice());
                            errandMap.put("waitPrice", order.getWaitPrice());
                            errandMap.put("runTimePrice", order.getTravelTimePrice());
                        }

                        errandMap.put("orderType", "errand");
                        errandMap.put("startPrice", order.getStartPrice());
                        errandMap.put("startLng", order.getStartLng());
                        errandMap.put("startLat", order.getStartLat());
                        errandMap.put("endLng", order.getDeliverLng());
                        errandMap.put("endLat", order.getDeliverLat());
                        errandMap.put("fromPlace", order.getStartAddress());
                        errandMap.put("toPlace", order.getDeliverAddress());
                        errandMap.put("passengerPhone", order.getPassengerPhone());
                        errandMap.put("passengerName", order.getPassengerName());
                        errandMap.put("companyAbbreviation", order.getCompanyName());
                        errandMap
                            .put("content", order.getContent() != null ? order.getContent() : "");
                        errandMap.put("buyNeeds",
                            order.getBuyNeeds() != null ? order.getBuyNeeds() : "");
                        errandMap.put("images", order.getImgs());
                        errandMap.put("errandType", order.getOrderType());
                        errandMap.put("errandValuationMethod", order.getErrandValuationMethod());
                        errandMap.put("shouldPay", order.getShouldPay());//应该支付的钱
                        errandMap.put("startDetailed", order.getStartDetailed());
                        errandMap.put("endDetailed", order.getEndDetailed());
                        errandMap.put("phone", order.getPhone());
                        errandMap.put("weight", order.getWeight());
                        errandMap.put("realPay", order.getRealPay());
                        errandMap.put("thanksCash", order.getThanksCash());
                        errandMap.put("goodsCash", order.getGoodsCash());
                        errandMap.put("addService", order.getAddServices());
                        List<ErrandOrderTypeOtherServices> otherServicesList = new ArrayList<ErrandOrderTypeOtherServices>();
                        if (StringUtils.isNotBlank(order.getAddServices())) {
                            String[] otherServices = order.getAddServices().split(",");
                            for (int i = 0; i < otherServices.length; i++) {
                                ErrandOrderTypeOtherServices errandOrderTypeOtherServices = errandService
                                    .getOtherServiceById(otherServices[i]);
                                otherServicesList.add(errandOrderTypeOtherServices);
                            }
                            order.setOtherServices(otherServicesList);
                        } else {
                            order.setOtherServices(new ArrayList<ErrandOrderTypeOtherServices>());
                        }
                        String tips = "";
                        if (StringUtils.isNotBlank(order.getTips())) {
                            String hotTips[] = order.getTips().split(",");
                            for (int i = 0; i < hotTips.length; i++) {
                                ErrandOrderTypeTips errandOrderTypeTips = errandService
                                    .getTipsById(hotTips[i]);
                                if (null != errandOrderTypeTips) {
                                    tips += errandOrderTypeTips.getTipName() + ",";
                                }
                            }
                        }
                        if (!StringUtils.isBlank(tips)) {
                            tips = tips.substring(0, tips.length() - 1);
                        }
                        errandMap.put("tips", tips);
                        errandMap.put("orderTypeOtherServices", order.getOtherServices());
                        StringBuilder buildermemo = new StringBuilder();
                        for (OrderMemo o : order.getMemoList()) {
                            buildermemo.append(o.getMemo() + ";");
                        }
                        errandMap.put("memo", buildermemo.toString());
                        if (null != order.getArea()) {
                            errandMap
                                .put("chargeStartTimes", order.getArea().getChargeStartTimes());
                        } else {
                            errandMap.put("chargeStartTimes", null);
                        }
                        errandOrdersMap.add(errandMap);
                    }
                }
                dataMap.put("errandTasks", errandOrdersMap);
                //----跑腿订单----
            }

            if (serviceSetting.isFreight()) {
                //----货运订单----
                List<com.ybkj.daijia.server.freight.Order> freightOrders = new ArrayList<com.ybkj.daijia.server.freight.Order>();
                List<Map<String, Object>> freightOrdersMap = new ArrayList<Map<String, Object>>();

                List<com.ybkj.daijia.server.freight.Order> newOrders_freight = new ArrayList<com.ybkj.daijia.server.freight.Order>();
                newOrders_freight = freightService.queryByEmployId(driver.getId(), "pai");
                if (CollectionUtils.isNotEmpty(newOrders_freight)) {
                    freightOrders.addAll(newOrders_freight);
                }

                List<com.ybkj.daijia.server.freight.Order> excuteTasks_freight = new ArrayList<com.ybkj.daijia.server.freight.Order>();
                excuteTasks_freight = freightService.queryByEmployId(driver.getId(), "waitorrun");

                if (CollectionUtils.isNotEmpty(excuteTasks_freight)) {
                    freightOrders.addAll(excuteTasks_freight);
                }

                if (CollectionUtils.isNotEmpty(freightOrders)) {
                    for (com.ybkj.daijia.server.freight.Order order : freightOrders) {
                        Map<String, Object> freightMap = new HashMap<String, Object>();
                        freightMap.put("orderId", order.getId());
                        freightMap.put("orderNumber", order.getOrderNo());
                        freightMap.put("time", order.getStartTime().getTime());
                        freightMap.put("status", order.getStatus());

                        freightMap.put("treatment", order.getTreatment());
                        if (order.getTreatment()) {
                            freightMap.put("realCash", order.getRealPay());
                            freightMap.put("guoluMoney", order.getGuoluMoney());
                            freightMap.put("yuanchengMoney", order.getYuanchengMoney());
                            freightMap.put("otherMoney", order.getOtherMoney());
                            freightMap.put("couponMoney", order.getCouponMoney());
                            freightMap.put("mileage", order.getMileage());
                            freightMap.put("waitedTime", order.getWaitTime());
                            freightMap.put("travelTime", order.getRunTime());
                            freightMap.put("startPrice", order.getStartPrice());
                            freightMap.put("mileagePrice", order.getMileagePrice());
                            freightMap.put("waitPrice", order.getWaitCost());
                            freightMap.put("runTimePrice", order.getRunTimePrice());
                        }

                        freightMap.put("orderType", "freight");
                        freightMap.put("startLng", order.getStartLng());
                        freightMap.put("startLat", order.getStartLat());
                        freightMap.put("endLng", order.getEndLng());
                        freightMap.put("endLat", order.getEndLat());
                        freightMap.put("fromPlace", order.getStartAddress());
                        freightMap.put("toPlace", order.getDestination());
                        freightMap.put("passengerPhone", order.getPassengerPhone());
                        freightMap.put("passengerName", order.getPassengerName());
                        freightMap.put("companyAbbreviation", order.getCompanyName());
                        freightMap.put("memo", order.getMemo());
                        freightMap.put("waypoints", order.getWaypoints());
                        freightMap.put("truckTypeName", order.getTruckTypeName());
                        freightMap.put("truckNumber", order.getTruckNumber());
                        freightMap.put("truckTypeId", order.getTruckTypeId());
                        freightMap.put("flitting", order.getFlitting());
                        freightMap.put("receipt", order.getReceipt());
                        freightMap.put("receivedPay", order.getReceivedPay());
                        freightMap.put("payMount", order.getPayMount());
                        freightMap.put("employId", order.getEmployId());
                        freightMap.put("employName", order.getEmployName());
                        freightMap.put("employPhone", order.getEmployPhone());
                        freightMap.put("budgetPay", order.getBudgetPay());//预算金额
                        freightMap.put("fixPrice", order.getFixedPrice());//是否定价
                        freightMap.put("fixPriceMoney", order.getFixPriceMoney());//定价金额
                        freightMap.put("shouldCash", order.getFixPriceMoney());//定价金额（新）
                        if (null != order.getArea()) {
                            freightMap
                                .put("chargeStartTimes", order.getArea().getChargeStartTimes());
                        } else {
                            freightMap.put("chargeStartTimes", null);
                        }
                        freightOrdersMap.add(freightMap);
                    }
                }
                dataMap.put("freightTasks", freightOrdersMap);
                //----货运订单----
            }
            if (serviceSetting.isZhuanxian()) {
                //----专线订单----
                List<com.ybkj.daijia.server.zhuanxian.Order> zhuanxianOrders = new ArrayList<com.ybkj.daijia.server.zhuanxian.Order>();
                List<Map<String, Object>> zhuanxianOrdersMap = new ArrayList<Map<String, Object>>();

                List<com.ybkj.daijia.server.zhuanxian.Order> newOrders_zhuanxian = new ArrayList<com.ybkj.daijia.server.zhuanxian.Order>();
                newOrders_zhuanxian = zhuanxianService.queryByEmployId(driver.getId(), "pai");
                if (CollectionUtils.isNotEmpty(newOrders_zhuanxian)) {
                    zhuanxianOrders.addAll(newOrders_zhuanxian);
                }

                List<com.ybkj.daijia.server.zhuanxian.Order> excuteTasks_zhuanxian = new ArrayList<com.ybkj.daijia.server.zhuanxian.Order>();
                excuteTasks_zhuanxian = zhuanxianService
                    .queryByEmployId(driver.getId(), "waitorrun");
                if (CollectionUtils.isNotEmpty(excuteTasks_zhuanxian)) {
                    zhuanxianOrders.addAll(excuteTasks_zhuanxian);
                }

                if (CollectionUtils.isNotEmpty(zhuanxianOrders)) {
                    for (com.ybkj.daijia.server.zhuanxian.Order order : zhuanxianOrders) {
                        Map<String, Object> zhuanxianMap = new HashMap<String, Object>();
                        zhuanxianMap.put("orderId", order.getId());
                        zhuanxianMap.put("zxOrderType", order.getOrderType());
                        zhuanxianMap.put("lineId", order.getLineId());
                        zhuanxianMap.put("lineName", order.getLineName());
                        zhuanxianMap.put("peopleNumber", order.getPeopleNumber());
                        zhuanxianMap.put("budgetPay", order.getBudgetPay());//预算金额
                        zhuanxianMap.put("orderNumber", order.getOrderNo());
                        zhuanxianMap.put("time", order.getServerTime().getTime());
                        zhuanxianMap.put("status", order.getStatus());

                        zhuanxianMap.put("treatment", order.getTreatment());
                        if (order.getTreatment()) {
                            zhuanxianMap.put("realCash", order.getRealPay());
                            zhuanxianMap.put("guoluMoney", order.getGuoluMoney());
                            zhuanxianMap.put("yuanchengMoney", order.getYuanchengMoney());
                            zhuanxianMap.put("otherMoney", order.getOtherMoney());
                            zhuanxianMap.put("couponMoney", order.getCouponMoney());
                            zhuanxianMap.put("mileage", order.getMileage());
                            zhuanxianMap.put("waitedTime", order.getStartWait());
                            zhuanxianMap.put("travelTime", order.getRunTime());
                            zhuanxianMap.put("startPrice", order.getStartPrice());
                            zhuanxianMap.put("mileagePrice", order.getMileagePrice());
                            zhuanxianMap.put("waitPrice", order.getWaitPrice());
                            zhuanxianMap.put("runTimePrice", order.getRunTimePrice());
                        }

                        zhuanxianMap.put("orderType", "zhuanxian");
                        zhuanxianMap.put("startLng", order.getStartLng());
                        zhuanxianMap.put("startLat", order.getStartLat());
                        zhuanxianMap.put("endLng", order.getEndLng());
                        zhuanxianMap.put("endLat", order.getEndLat());
                        zhuanxianMap.put("fromPlace", order.getStartAddress());
                        zhuanxianMap.put("toPlace", order.getEndAddress());
                        zhuanxianMap.put("passengerPhone",
                            StringUtils.isNotBlank(order.getShowPhone()) ? order.getShowPhone()
                                : order.getPassengerPhone());
                        zhuanxianMap.put("passengerName",
                            StringUtils.isNotBlank(order.getShowName()) ? order.getShowName()
                                : order.getPassengerName());
                        zhuanxianMap.put("companyAbbreviation", order.getCompanyName());
                        zhuanxianMap.put("companyId", order.getCompanyId());
                        zhuanxianMap.put("takeDeliveryName", order.getTakeDeliveryName());
                        zhuanxianMap.put("takeDeliveryPhone", order.getTakeDeliveryPhone());
                        String memo = "";
                        if (com.ybkj.daijia.server.zhuanxian.Order.TYPE_JIHUO
                            .equals(order.getOrderType())) {
                            memo = "收货人:(" + order.getTakeDeliveryName() + ") 、  收货人电话:(" + order
                                .getTakeDeliveryPhone() + ")";
                        }
                        memo += (((StringUtils.isNotBlank(order.getMemo())) ? order.getMemo() + ";"
                            : ""));
                        zhuanxianMap.put("memo", memo);
                        Line line = zhuanxianService.findByLine(order.getLineId());
                        if (order.getOrderType()
                            .equals(com.ybkj.daijia.server.zhuanxian.Order.TYPE_BAOCHE)) {
                            Area bcarea = areaService.findOneWithCharge(line.getBaocheAreaId());
                            zhuanxianMap.put("chargeStartTimes",
                                bcarea == null ? null : bcarea.getChargeStartTimes());
                        } else if (order.getOrderType()
                            .equals(com.ybkj.daijia.server.zhuanxian.Order.TYPE_JIHUO)) {
                            Area jharea = areaService.findOneWithCharge(line.getJihuoAreaId());
                            zhuanxianMap.put("chargeStartTimes",
                                jharea == null ? null : jharea.getChargeStartTimes());
                        } else if (order.getOrderType()
                            .equals(com.ybkj.daijia.server.zhuanxian.Order.TYPE_PINCHE)) {
                            Area pcarea = areaService.findOneWithCharge(line.getAreaId());
                            zhuanxianMap.put("chargeStartTimes",
                                pcarea == null ? null : pcarea.getChargeStartTimes());
                        } else {
                            zhuanxianMap.put("chargeStartTimes", null);
                        }
                        zhuanxianMap.put("showPhone", order.getShowPhone());
                        zhuanxianMap.put("showName", order.getShowName());

                        zhuanxianOrdersMap.add(zhuanxianMap);
                    }
                }
                dataMap.put("zhuanxianTasks", zhuanxianOrdersMap);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(dataMap);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver indexOrders error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 司机查询账户明细
     * @param employToken
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping(value = "queryPayments", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryPayments(String employToken, Integer page, Integer limit) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Page<Map<String, Object>> pages = driverPaymentsRecordService
                .queryByEmply2(driver.getId(), null, null, null, null, page, limit);
            List<Map<String, Object>> todayRecordsMap = new ArrayList<Map<String, Object>>();
            if (pages.getTotalElements() > 0) {
                todayRecordsMap.addAll(pages.getContent());
            }
            Pageable pageable = new PageRequest(page, limit);
            Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(todayRecordsMap,
                pageable, pages.getTotalElements());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(newPages);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver indexPayments error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 补单
     * @param driverID
     * @param xml
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "fillOrder", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport fillOrder(
        String employToken,
        String fromPlace, Double clientLongitude, Double clientLatitude,
        String toPlace, Double toPlaceLongitude, Double toPlaceLatitude,
        boolean djxNeed, boolean ywxNeed, BigDecimal budgetPay, Long areaId,
        String clientName, String clientPhone, Long serverTimeStamp) {

        logger.debug(
            "recv employToken:{},fromPlace:{},clientLongitude:{},clientLatitude:{},clientName:{},clientPhone:{},serverTimeStamp:{}",
            employToken, fromPlace, clientLongitude, clientLatitude, clientName, clientPhone,
            serverTimeStamp);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(fromPlace)
            || null == clientLongitude || null == clientLatitude ||
            StringUtils.isBlank(clientPhone) || null == serverTimeStamp) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "您还没有上班，不能补单"));
            } else {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "当前状态忙碌，暂不能补单"));
            }
        }

        if (!driver.getDriverJobType().equals(Driver.DriverJobType.all)) {
            if (!driver.getDriverJobType().contains(Driver.DriverJobType.daijia.toString())) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_IS_DAIJIA_ERROR);
            }
        }

        try {
            Order order = new Order();

            order.setFromPlace(fromPlace);
            order.setClientLongitude(clientLongitude);
            order.setClientLatitude(clientLatitude);
            order.setToPlace(toPlace);
            order.setToPlaceLongitude(toPlaceLongitude);
            order.setToPlaceLatitude(toPlaceLatitude);
            order.setClientName(clientName);
            order.setClientPhone(clientPhone.replaceAll(" ", ""));
            order.setServerTime(new Date(serverTimeStamp));
            order.setStatus(Order.ORDER_STATUS_NEW);
            order.setOrderCarType(OrderCarType.daijia);
            order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);
            order.setShouldCash(budgetPay);
            order.setAreaOfEmployId(areaId);

            if (djxNeed || ywxNeed) {
                Company company = companyService.findOne(driver.getCompanyId());
                if (djxNeed) {
                    order.setDjxFee(company.getDjxFee());
                }
                if (ywxNeed) {
                    order.setYwxFee(company.getYwxFee());
                }
            }

            Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());

            Result<Order> result = orderService.fillOrderV2(order, driver.getId());

            if (!result.isSuccess()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }

            if (null == passenger) {
                passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //补单成功
            instance.setData(order.getId());

            //补单v2事件
            OrderFillV2Event fillV2Event = new OrderFillV2Event(order);
            applicationEventMulticaster.multicastEvent(fillV2Event);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver fillOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 补单
     * @param driverID
     * @param xml
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "fillOrderV4", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport fillOrderV4(
        String employToken,
        String fromPlace, Double clientLongitude, Double clientLatitude,
        String toPlace, Double toPlaceLongitude, Double toPlaceLatitude,
        boolean djxNeed, boolean ywxNeed, BigDecimal budgetPay, Long areaId,
        String clientName, String clientPhone, Long serverTimeStamp) {

        logger.debug(
            "recv employToken:{},fromPlace:{},clientLongitude:{},clientLatitude:{},clientName:{},clientPhone:{},serverTimeStamp:{}",
            employToken, fromPlace, clientLongitude, clientLatitude, clientName, clientPhone,
            serverTimeStamp);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(fromPlace)
            || null == clientLongitude || null == clientLatitude ||
            StringUtils.isBlank(clientPhone) || null == serverTimeStamp) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "您还没有上班，不能补单"));
            } else {
                return ResultTransport.getErrorBy(
                    new Error(ErrorConstantV4.EMPLOY_STATUS_ERROR.getCode(), "有未完成的工单，暂不能补单"));
            }
        }

        if (!driver.getDriverJobType().equals(Driver.DriverJobType.all)) {
            if (!driver.getDriverJobType().contains(Driver.DriverJobType.daijia.toString())) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_IS_DAIJIA_ERROR);
            }
        }

        try {
            Order order = new Order();

            order.setFromPlace(fromPlace);
            order.setClientLongitude(clientLongitude);
            order.setClientLatitude(clientLatitude);
            order.setToPlace(toPlace);
            order.setToPlaceLongitude(toPlaceLongitude);
            order.setToPlaceLatitude(toPlaceLatitude);
            order.setClientName(clientName);
            order.setClientPhone(clientPhone.replaceAll(" ", ""));
            order.setServerTime(new Date(serverTimeStamp));
            order.setStatus(Order.ORDER_STATUS_NEW);
            order.setOrderCarType(OrderCarType.daijia);
            order.setOrderCarTypeDetail(OrderCarTypeDetail.jhdj);
            order.setShouldCash(budgetPay);
            order.setAreaOfEmployId(areaId);

            Company company = companyService.findOne(driver.getCompanyId());
            if (company.getAllowDjx()) {
                if (djxNeed) {
                    order.setDjxFee(company.getDjxFee());
                }
            } else {
                order.setDjxFee(company.getDjxFee());
            }

            if (company.getAllowYwx()) {
                if (ywxNeed) {
                    order.setYwxFee(company.getYwxFee());
                }
            } else {
                order.setYwxFee(company.getYwxFee());
            }

            Passenger passenger = memberService.findOnePassengerByPhone(order.getClientPhone());

            Result<Order> result = orderService.fillOrderV4(order, driver.getId());

            if (!result.isSuccess()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }

            if (null == passenger) {
                passenger = memberService.findOnePassengerByPhone(order.getClientPhone());
                ReactorVo rVo = new ReactorVo();
                rVo.setPassenger(passenger);
                rVo.setActivityEvent(ActivityEvent.newRegister);
                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo);
                applicationEventMulticaster.multicastEvent(activityCheckEvent);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //补单成功
            instance.setData(order.getId());

            //补单v2事件
            OrderFillV2Event fillV2Event = new OrderFillV2Event(order);
            applicationEventMulticaster.multicastEvent(fillV2Event);

            OrderRecordEvent orderRecordEvent = new OrderRecordEvent(order);
            applicationEventMulticaster.multicastEvent(orderRecordEvent);

            return instance;

        } catch (Exception e) {
            logger.error("api v4 driver fillOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 接受工单
     *
     * @return
     */
    @RequestMapping(value = "acceptTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport acceptTask(String employToken, Long orderId) {

        logger.debug("recv employToken:{},orderId:{}", employToken, orderId);

        if (StringUtils.isBlank(employToken) || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (Order.ORDER_STATUS_YIPAIDAN != order.getStatus()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {

            orderService.accept(order, driver);

            //接受工单事件
            OrderAcceptEvent acceptEvent = new OrderAcceptEvent(order);
            applicationEventMulticaster.multicastEvent(acceptEvent);

//			Company thisCompany=companyService.findOne(order.getCompanyId());
//			Area area=null;
//			Area daijiaArea=null;
//			if(passenger.getType().equals(Passenger.TYPE_PASSENGER)){
//				daijiaArea=areaService.findDaijiaByPassenger(passenger.getId());
//			}
//			else if(passenger.getType().equals(Passenger.TYPE_ENTERPRISE)){
//				daijiaArea=areaService.findDaijiaByEnterprise(passenger.getEnterprise_id());
//			}
//
//			if(null!=daijiaArea){
//				area=areaService.findOneWithCharge(daijiaArea.getId());
//			}
//			else{
//				area=areaService.findOneWithCharge(thisCompany.getAreaId());
//			}

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS); //接单成功
            instance.setData(order);//投保用
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver acceptTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 改变目的地
     * @param driverID
     * @param orderID
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "changeToPlace", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport changeToPlace(String employToken, Long orderId,
        String toPlace, Double longitude, Double latitude) {

        logger.debug("recv employToken:{},orderId:{},toPlace:{},longitude:{},latitude:{}",
            employToken, orderId, toPlace, longitude, latitude);

        if (StringUtils.isBlank(employToken) || null == orderId || StringUtils.isBlank(toPlace)
            || null == longitude || null == latitude) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (Order.ORDER_STATUS_BUSY != order.getStatus()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        try {

            order.setToPlace(toPlace);
            order.setToPlaceLatitude(latitude);
            order.setToPlaceLongitude(longitude);
            orderService.update(order);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver changeToPlace error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 服务协议(优先选子公司)
     */
    @RequestMapping("agreement")
    public String agreement(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude,
        @RequestParam(required = false, value = "employToken") String employToken,
        Model model) {
        logger.debug("recv acKey:{},longitude:{},latitude:{},employToken:{}", acKey, longitude,
            latitude, employToken);

        String agreement = null;
        Driver driver = null;

        if (StringUtils.isNotBlank(employToken)) {
            DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

            if (null == driverLogin) {
                return "driver/agreement";
            }

            if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
                return "driver/agreement";
            }

            driver = driverService.findOne(driverLogin.getDriverId());

            if (null == driver) {
                return "driver/agreement";
            }
        }

        if (StringUtils.isNotBlank(acKey)) {
            Company company = companyService.findByAppKey(acKey);
            if (StringUtils.isNotBlank(company.getAgreementEmploy())) {
                agreement = company.getAgreementEmploy();
            } else {
                agreement = companyService.getMain().getAgreementEmploy();
            }
        } else {
            String city = "";
            if (null != longitude && null != latitude) {
                city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
            }
            List<Company> companyList = null;
            if (StringUtils.isNotBlank(city)) {
                companyList = companyService.findByAreaCityName(city);
            }
            if (!CollectionUtils.isEmpty(companyList)) {

                List<Company> notMainCompanys = new ArrayList<Company>();
                Company cityMainCompany = null;

                for (Company c : companyList) {
                    if (null != driver && driver.getCompanyId().equals(c.getId())) {
                        agreement = c.getAgreementEmploy();
                        break;
                    }

                    if (!c.isCompanyType()) {
                        if (StringUtils.isBlank(c.getAppKey())) {
                            notMainCompanys.add(c);
                        }
                    } else {
                        cityMainCompany = c;
                    }
                }

                if (StringUtils.isBlank(agreement)) {
                    if (!CollectionUtils.isEmpty(notMainCompanys)) {
                        agreement = notMainCompanys
                            .get(new Random().nextInt(notMainCompanys.size())).getAgreementEmploy();
                    }
                }

                if (StringUtils.isBlank(agreement)) {
                    if (null != cityMainCompany) {
                        agreement = cityMainCompany.getAgreementEmploy();
                    }
                }
            }
        }
        if (StringUtils.isBlank(agreement)) {
            agreement = companyService.getMain().getAgreementEmploy();
        }

        model.addAttribute("agreement", HtmlHelper.htmlscripttext(agreement));

        return "driver/agreement";

    }

    /**
     * 服务协议(优先选子公司)(过APP评测)
     */
    @RequestMapping("agreement2")
    public @ResponseBody
    ResultTransport agreemen2t(
        @RequestParam(required = false, value = "acKey") String acKey,
        @RequestParam(required = false, value = "longitude") Double longitude,
        @RequestParam(required = false, value = "latitude") Double latitude,
        @RequestParam(required = false, value = "employToken") String employToken,
        HttpServletRequest request) {

        String agreement = null;
        Driver driver = null;

        if (StringUtils.isNotBlank(employToken)) {
            DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

            if (null == driverLogin) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
            }

            if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
            }

            driver = driverService.findOne(driverLogin.getDriverId());

            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
            }

            if (driver.getIsFreeze()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
            }
        }

        if (StringUtils.isNotBlank(acKey)) {
            Company company = companyService.findByAppKey(acKey);
            if (StringUtils.isNotBlank(company.getAgreementEmploy())) {
                agreement = company.getAgreementEmploy();
            } else {
                agreement = companyService.getMain().getAgreementEmploy();
            }
        } else {
            String city = "";
            if (null != longitude && null != latitude) {
                city = HttpClientUtil.getCityByLngAndLat(longitude, latitude);
            }
            List<Company> companyList = null;
            if (StringUtils.isNotBlank(city)) {
                companyList = companyService.findByAreaCityName(city);
            }
            if (!CollectionUtils.isEmpty(companyList)) {

                List<Company> notMainCompanys = new ArrayList<Company>();
                Company cityMainCompany = null;

                for (Company c : companyList) {
                    if (null != driver && driver.getCompanyId().equals(c.getId())) {
                        agreement = c.getAgreementEmploy();
                        break;
                    }

                    if (!c.isCompanyType()) {
                        if (StringUtils.isBlank(c.getAppKey())) {
                            notMainCompanys.add(c);
                        }
                    } else {
                        cityMainCompany = c;
                    }
                }

                if (StringUtils.isBlank(agreement)) {
                    if (!CollectionUtils.isEmpty(notMainCompanys)) {
                        agreement = notMainCompanys
                            .get(new Random().nextInt(notMainCompanys.size())).getAgreementEmploy();
                    }
                }

                if (StringUtils.isBlank(agreement)) {
                    if (null != cityMainCompany) {
                        agreement = cityMainCompany.getAgreementEmploy();
                    }
                }
            }
        }
        if (StringUtils.isBlank(agreement)) {
            agreement = companyService.getMain().getAgreementEmploy();
        }

        try {
            String path = String.format("%s/WEB-INF/views/driver/", Config.getWebapp());

            Configuration cfg = new Configuration();

            cfg.setTemplateLoader(new FileTemplateLoader(new File(path)));
            cfg.setDefaultEncoding("UTF-8");

            Template template = cfg.getTemplate("agreement2.ftl");

            Map<String, Object> root = new HashMap<String, Object>();
            root.put("ctx", request.getContextPath());
            root.put("agreement", HtmlHelper.htmlscripttext(agreement));

            StringWriter writer = new StringWriter();
            template.process(root, writer);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            Map<String, String> datamap = new HashMap<String, String>();
            datamap.put("content", HtmlHelper.replaceBlank(writer.toString()));
            instance.setData(datamap);
            return instance;

        } catch (IOException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        } catch (TemplateException e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "sameOrderEmploys", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport sameOrderEmploys(String employToken, Long orderId) {

        logger.debug("recv employToken:{}", employToken);

        if (StringUtils.isBlank(employToken) || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            Setting setting = settingUtils.get();

            List<Map<String, Object>> driverMapList = new ArrayList<Map<String, Object>>();

            if (null != order.getOrderGroupId()) {
                OrderGroup orderGroup = orderGroupService.findOne(order.getOrderGroupId());
                if (null != orderGroup) {
                    List<Order> groupsOrders = orderService.findByGroup(order.getOrderGroupId());
                    if (!CollectionUtils.isEmpty(groupsOrders)) {
                        for (Order o : groupsOrders) {
                            if (null != o.getDriverId()) {
                                Driver d = driverService.findOne(o.getDriverId());
                                if (null != d) {
//								if(null!=d && !d.getId().equals(driver.getId())){
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("realName", d.getRealname());
                                    map.put("userName", d.getUsername());
                                    map.put("phone", d.getPhone());

                                    if (StringUtils.isNotBlank(d.getPhoto())) {
                                        map.put("photo",
                                            setting.getWebUrl() + "/upload/driver/" + d.getPhoto());
                                    } else {
                                        map.put("photo", null);
                                    }

                                    if (o.getStatus().equals(Order.ORDER_STATUS_YIPAIDAN)) {
                                        map.put("status", 1);
                                    } else if (o.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
                                        if (null == o.getStartDriveDate()) {
                                            map.put("status", 2);
                                        } else {
                                            map.put("status", 3);
                                        }
                                    } else if (o.getStatus().equals(Order.ORDER_STATUS_FINISHED)
                                        || o.getStatus().equals(Order.ORDER_STATUS_BAODAN)) {
                                        map.put("status", 4);
                                    }

                                    if (orderGroup.getDriverId().equals(d.getId())) {
                                        map.put("leader", true);
                                    } else {
                                        map.put("leader", false);
                                    }

                                    driverMapList.add(map);
                                }
                            }
                        }
                    }
                }


            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(driverMapList);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver sameOrderEmploys error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "queryOrders", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport queryOrders(String employToken, String orderType, String dateType, Integer page,
        Integer limit) {

        logger.debug("recv employToken:{},orderType:{},dateType:{},page:{},limit:{}", employToken,
            orderType, dateType, page, limit);

        if (StringUtils.isBlank(employToken) || StringUtils.isBlank(orderType) || StringUtils
            .isBlank(dateType) || null == page || null == limit) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        try {

            Setting setting = settingUtils.get();

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            //统计
            Calendar nowCalendar = Calendar.getInstance();
            int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);
            //查询今日
            Calendar calendaer = Calendar.getInstance();
            calendaer.set(Calendar.HOUR_OF_DAY, setting.getWorkBegin());
            calendaer.set(Calendar.MINUTE, 0);
            calendaer.set(Calendar.SECOND, 0);
            Date end = calendaer.getTime();
            Date begin = DateUtils.addHours(end, -24);
            if (setting.getWorkBegin() <= nowHour) {
                end = DateUtils.addHours(end, 24);
                begin = DateUtils.addHours(begin, 24);
            }

            if (dateType.equals("today")) {

            } else if (dateType.equals("yesterday")) {
                begin = DateUtils.addHours(begin, -24);
                end = DateUtils.addHours(end, -24);
            } else if (dateType.equals("thismonth")) {
                Calendar c = Calendar.getInstance();
                c.setTime(begin);
                c.set(Calendar.DAY_OF_MONTH, 1);
                begin = c.getTime();
            } else if (dateType.equals("lastmonth")) {
                Calendar c = Calendar.getInstance();
                c.setTime(begin);
                c.set(Calendar.DAY_OF_MONTH, 1);
                end = c.getTime();
                begin = DateUtils.addMonths(end, -1);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            if (orderType.equals("daijia")) {
                if (serviceSetting.isDaijia()) {
                    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
                    Page<Order> pageOrder = orderService
                        .findByDriverAndFinishTime(driver.getId(), begin, end, page, limit);
                    if (pageOrder.getTotalElements() > 0) {
                        for (Order order : pageOrder.getContent()) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("orderId", order.getId());
                            map.put("orderNumber", order.getOrderNumber());
                            map.put("time", order.getFinishTime().getTime());
                            map.put("fromPlace", order.getFromPlace());
                            map.put("toPlace", order.getToPlace());
                            map.put("baoxiao", order.isBaoxiao());
                            DriverPaymentsRecord paymentsRecord = driverPaymentsRecordService
                                .findOrderRecharge(driver.getId(), order.getId(),
                                    DriverPaymentsRecord.ORDER_TYPE_DAIJIA);
                            if (null != paymentsRecord) {
                                map.put("realCash", paymentsRecord.getMoney());
                            } else {
                                map.put("realCash", BigDecimal.ZERO);
                            }
                            mapList.add(map);
                        }
                    }
                    Pageable pageable = new PageRequest(page, limit);
                    Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(mapList,
                        pageable, pageOrder.getTotalElements());
                    instance.setData(newPages);
                }
            } else if (orderType.equals("zhuanche")) {
                if (serviceSetting.isZhuanche()) {
                    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
                    Page<com.ybkj.daijia.server.zhuan.Order> pageOrder = zhuancheService
                        .findByDriverAndFinishTime(driver.getId(), begin, end, page, limit);
                    if (pageOrder.getTotalElements() > 0) {
                        for (com.ybkj.daijia.server.zhuan.Order order : pageOrder.getContent()) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("orderId", order.getId());
                            map.put("orderNumber", order.getOrderNo());
                            map.put("time", order.getFinishTime().getTime());
                            map.put("fromPlace", order.getStartAddress());
                            map.put("toPlace", order.getEndAddress());
                            map.put("baoxiao", order.isBaoxiao());
                            DriverPaymentsRecord paymentsRecord = driverPaymentsRecordService
                                .findOrderRecharge(driver.getId(), order.getId(),
                                    DriverPaymentsRecord.ORDER_TYPE_ZHUANCHE);
                            if (null != paymentsRecord) {
                                map.put("realCash", paymentsRecord.getMoney());
                            } else {
                                map.put("realCash", BigDecimal.ZERO);
                            }
                            mapList.add(map);
                        }

                    }
                    Pageable pageable = new PageRequest(page, limit);
                    Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(mapList,
                        pageable, pageOrder.getTotalElements());
                    instance.setData(newPages);
                }
            } else if (orderType.equals("errand")) {
                if (serviceSetting.isPaotui()) {
                    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
                    Page<com.ybkj.daijia.server.errand.Order> pageOrder = errandService
                        .findByDriverAndFinishTime(driver.getId(), begin, end, page, limit);
                    if (pageOrder.getTotalElements() > 0) {
                        for (com.ybkj.daijia.server.errand.Order order : pageOrder.getContent()) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("orderId", order.getId());
                            map.put("orderNumber", order.getOrderNo());
                            map.put("time", order.getFinishTime().getTime());
                            map.put("fromPlace", order.getStartAddress());
                            map.put("toPlace", order.getDeliverAddress());
                            map.put("baoxiao", order.isBaoxiao());
                            DriverPaymentsRecord paymentsRecord = driverPaymentsRecordService
                                .findOrderRecharge(driver.getId(), order.getId(),
                                    DriverPaymentsRecord.ORDER_TYPE_PAOTUI);
                            if (null != paymentsRecord) {
                                map.put("realCash", paymentsRecord.getMoney());
                            } else {
                                map.put("realCash", BigDecimal.ZERO);
                            }
                            mapList.add(map);
                        }
                    }
                    Pageable pageable = new PageRequest(page, limit);
                    Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(mapList,
                        pageable, pageOrder.getTotalElements());
                    instance.setData(newPages);
                }
            } else if (orderType.equals("freight")) {
                if (serviceSetting.isFreight()) {
                    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
                    Page<com.ybkj.daijia.server.freight.Order> pageOrder = freightService
                        .findByDriverAndFinishTime(driver.getId(), begin, end, page, limit);
                    if (pageOrder.getTotalElements() > 0) {
                        for (com.ybkj.daijia.server.freight.Order order : pageOrder.getContent()) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("orderId", order.getId());
                            map.put("orderNumber", order.getOrderNo());
                            map.put("time", order.getFinishTime().getTime());
                            map.put("fromPlace", order.getStartAddress());
                            map.put("toPlace", order.getDestination());
                            map.put("baoxiao", order.isBaoxiao());
                            DriverPaymentsRecord paymentsRecord = driverPaymentsRecordService
                                .findOrderRecharge(driver.getId(), order.getId(),
                                    DriverPaymentsRecord.ORDER_TYPE_FREIGHT);
                            if (null != paymentsRecord) {
                                map.put("realCash", paymentsRecord.getMoney());
                            } else {
                                map.put("realCash", BigDecimal.ZERO);
                            }
                            mapList.add(map);
                        }
                    }
                    Pageable pageable = new PageRequest(page, limit);
                    Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(mapList,
                        pageable, pageOrder.getTotalElements());
                    instance.setData(newPages);
                }
            } else if (orderType.equals("zhuanxian")) {
                if (serviceSetting.isZhuanxian()) {
                    List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
                    Page<com.ybkj.daijia.server.zhuanxian.Order> pageOrder = zhuanxianService
                        .findByDriverAndFinishTime(driver.getId(), begin, end, page, limit);
                    if (pageOrder.getTotalElements() > 0) {
                        for (com.ybkj.daijia.server.zhuanxian.Order order : pageOrder
                            .getContent()) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("orderId", order.getId());
                            map.put("orderNumber", order.getOrderNo());
                            map.put("time", order.getFinishTime().getTime());
                            map.put("fromPlace", order.getStartAddress());
                            map.put("toPlace", order.getEndAddress());
                            map.put("baoxiao", order.isBaoxiao());
                            DriverPaymentsRecord paymentsRecord = driverPaymentsRecordService
                                .findOrderRecharge(driver.getId(), order.getId(),
                                    DriverPaymentsRecord.ORDER_TYPE_ZHUANXIAN);
                            if (null != paymentsRecord) {
                                map.put("realCash", paymentsRecord.getMoney());
                            } else {
                                map.put("realCash", BigDecimal.ZERO);
                            }
                            mapList.add(map);
                        }
                    }
                    Pageable pageable = new PageRequest(page, limit);
                    Page<Map<String, Object>> newPages = new PageImpl<Map<String, Object>>(mapList,
                        pageable, pageOrder.getTotalElements());
                    instance.setData(newPages);
                }
            }

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver queryOrders error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "arrivePlace", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport arrivePlace(String employToken, Long orderId) {

        logger.debug("recv employToken:{},orderId:{}", employToken, orderId);

        if (StringUtils.isBlank(employToken) || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (Order.ORDER_STATUS_BUSY != order.getStatus()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

//		if(null!=order.getArrivePlaceDate()){
//          return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
//        }

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        try {

            orderService.arrivePlaceV4(order);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver arrivePlace error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "startDrive", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport startDrive(
        String employToken, Long orderId, Integer waiteTime) {

        logger
            .debug("recv employToken:{},orderId:{},waiteTime:{}", employToken, orderId, waiteTime);

        if (StringUtils.isBlank(employToken) || null == orderId || null == waiteTime) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

//		if(null!=order.getStartDriveDate()){
//			return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
//		}

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        try {

            orderService.startDriveV4(order, waiteTime);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(order);//投保用
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver startDrive error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * 获取订单信息
     * @param id
     * @return
     */
    @RequestMapping(value = "getOrderInfo", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport getOrderInfo(Long orderId) {

        logger.debug("recv orderId:{}", orderId);

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            Company thisCompany = companyService.findOne(order.getCompanyId());

            Area area = null;
            //客户经理单独收费
            if (null != order.getManagerId()) {
                WeixinManager weixinManager = weixinManagerService.findOne(order.getManagerId());
                if (null != weixinManager && null != weixinManager.getAreaId()) {
                    area = areaService.findOneWithCharge(weixinManager.getAreaId());
                }
            }

            if (null == area) {
                //客户等级单独收费
                if (null != passenger.getGrade_id()) {
                    PassengerGrade passengerGrade = memberService
                        .findOneGrade(passenger.getGrade_id());
                    if (null != passengerGrade) {
                        if (null != passengerGrade.getDaijiaAreaId()) {
                            area = areaService.findOneWithCharge(passengerGrade.getDaijiaAreaId());
                        }
                    }
                }
            }

            if (null == area) {
                area = areaService.findOneWithCharge(thisCompany.getAreaId());
            }

            Map<String, Object> daijiaMap = new HashMap<String, Object>();
            daijiaMap.put("orderId", order.getId());
            daijiaMap.put("orderNumber", order.getOrderNumber());
            daijiaMap.put("time", order.getServerTime().getTime());
            if (null != order.getStartDriveDate()) {
                daijiaMap.put("status", 4);
            } else if (null != order.getArrivePlaceDate()) {
                daijiaMap.put("status", 3);
            } else {
                daijiaMap.put("status", order.getStatus());
            }

            daijiaMap.put("treatment", order.isTreatment());
            if (order.isTreatment()) {
                daijiaMap.put("realCash", order.getRealCash());
                daijiaMap.put("guoluMoney", order.getGuoluMoney());
                daijiaMap.put("yuanchengMoney", order.getYuanchengMoney());
                daijiaMap.put("otherMoney", order.getOtherMoney());
                daijiaMap.put("couponMoney", order.getCouponMoney());
                daijiaMap.put("mileage", order.getMileage());
                daijiaMap.put("waitedTime", order.getWaitedTime());
                daijiaMap.put("travelTime", order.getTravelTime());
                daijiaMap.put("startPrice", order.getStartPrice());
                daijiaMap.put("mileagePrice", order.getMileagePrice());
                daijiaMap.put("waitPrice", order.getWaitedPrice());
                daijiaMap.put("runTimePrice", order.getTravelPrice());
            }

            daijiaMap.put("startLng", order.getClientLongitude());
            daijiaMap.put("startLat", order.getClientLatitude());
            daijiaMap.put("endLng", order.getToPlaceLongitude());
            daijiaMap.put("endLat", order.getToPlaceLatitude());
            daijiaMap.put("fromPlace", order.getFromPlace());
            daijiaMap.put("toPlace", order.getToPlace());
            daijiaMap.put("passengerPhone", order.getUserPhone());
            daijiaMap.put("passengerName", order.getClientName());
            daijiaMap.put("companyAbbreviation", thisCompany.getAbbreviation());
            daijiaMap.put("memo", order.getMemo());
            if (order.isFixPrice()) {
                daijiaMap.put("fixPrice", true);
            } else {
                daijiaMap.put("fixPrice", false);
            }
            daijiaMap.put("shouldCash", order.getShouldCash());
            daijiaMap.put("orderType", "daijia");

            boolean hasAreaOfEmploy = false;

            if (null != order.getAreaOfEmployId()) {
                AreaOfEmploy areaOfEmploy = areaOfEmployService
                    .findOneWithCharge(order.getAreaOfEmployId());

                if (null != areaOfEmploy) {
                    daijiaMap.put("chargeStartTimes", areaOfEmploy.getChargeStartTimes());

                    hasAreaOfEmploy = true;
                }
            }
            if (!hasAreaOfEmploy) {
                daijiaMap.put("chargeStartTimes", area.getChargeStartTimes());
            }

            instance.setData(daijiaMap);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver getOrderInfo error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }
    }

    /**
     * 提交抢单
     * @param driverId
     * @param orderId
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "getRushOrder", method = RequestMethod.POST)
    public synchronized @ResponseBody
    ResultTransport getRushOrder(String employToken, Long orderId) {

        logger.debug("recv employToken:{},orderId:{}", employToken, orderId);

        if (StringUtils.isBlank(employToken) || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowRushOrder()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_RUSH_CANCELED);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_STATUS_ERROR);
        }

        if (!driver.getDriverJobType().contains(Driver.DriverJobType.daijia.toString())) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_IS_DAIJIA_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HASBEEN_RUSHED);
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {

            orderService.getRushOrder(driver, order);
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

//			Company thisCompany=companyService.findOne(order.getCompanyId());
//			Area area=null;
//			Area daijiaArea=null;
//			if(passenger.getType().equals(Passenger.TYPE_PASSENGER)){
//				daijiaArea=areaService.findDaijiaByPassenger(passenger.getId());
//			}
//			else if(passenger.getType().equals(Passenger.TYPE_ENTERPRISE)){
//				daijiaArea=areaService.findDaijiaByEnterprise(passenger.getEnterprise_id());
//			}
//
//			if(null!=daijiaArea){
//				area=areaService.findOneWithCharge(daijiaArea.getId());
//			}
//			else{
//				area=areaService.findOneWithCharge(thisCompany.getAreaId());
//			}

//			Map<String, Object> daijiaMap=new HashMap<String, Object>();
//			daijiaMap.put("orderId", order.getId());
//			daijiaMap.put("orderNumber", order.getOrderNumber());
//			daijiaMap.put("time", order.getServerTime().getTime());
//			daijiaMap.put("status", order.getStatus());
//			daijiaMap.put("startLng", order.getClientLongitude());
//			daijiaMap.put("startLat", order.getClientLatitude());
//			daijiaMap.put("endLng", order.getToPlaceLongitude());
//			daijiaMap.put("endLat", order.getToPlaceLatitude());
//			daijiaMap.put("fromPlace", order.getFromPlace());
//			daijiaMap.put("toPlace", order.getToPlace());
//			daijiaMap.put("orderType", "daijia");
//			daijiaMap.put("chargeStartTimes", area.getChargeStartTimes());

//			instance.setData(daijiaMap);

            instance.setData(order);//投保用
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver getRushOrder error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 拒单
     * @return
     */
    @RequestMapping(value = "refuseTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport refuseTask(String employToken, Long orderId, String cause) {

        logger.debug("recv employToken:{},orderId:{},cause:{}", employToken, orderId, cause);

        if (StringUtils.isBlank(employToken) || null == orderId || StringUtils.isBlank(cause)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (Order.ORDER_STATUS_YIPAIDAN != order.getStatus()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        try {

            orderService.refuse(order, cause);

            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //申请销单成功

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver refuseTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "cancelTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport cancelTask(String employToken, Long orderId, String cause) {

        logger.debug("recv employToken:{},orderId:{},cause:{}", employToken, orderId, cause);

        if (StringUtils.isBlank(employToken) || null == orderId || StringUtils.isBlank(cause)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowDriverCancel()) {
            return ResultTransport.getErrorBy(ErrorConstant.DRIVER_CANNOT_CANCEL_ORDER);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }

        if (null != order.getStartDriveDate()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        try {
            orderService.driverCancel(order, cause);
            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS); //司机销单成功

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver cancelTask error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "baoxiao", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport baoxiao(String employToken, Long orderId, String orderType, BigDecimal money,
        String memo) {

        logger.debug("recv employToken:{},orderId:{},money:{},memo:{}", employToken, orderId, money,
            memo);

        if (StringUtils.isBlank(employToken) || null == orderId || null == money || StringUtils
            .isBlank(memo)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Setting setting = settingUtils.get();
        if (!setting.isAllowBaoxiao()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.CAN_NOT_ALLOW_BAOXIAO);
        }

        Integer financialOrderType = null;
        Long orderCompanyId = null;
        String orderNumber = "";

        if ("daijia".equals(orderType)) {
            Order order = orderService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
            }
            if (order.isBaoxiao()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_BAOXIAO);
            }
            financialOrderType = FinancialRecord.ORDER_TYPE_DAIJIA;
            orderCompanyId = order.getCompanyId();
            orderNumber = order.getOrderNumber();
        } else if ("zhuanche".equals(orderType)) {
            com.ybkj.daijia.server.zhuan.Order order = zhuancheService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
            }
            if (order.isBaoxiao()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_BAOXIAO);
            }
            financialOrderType = FinancialRecord.ORDER_TYPE_ZHUANCHE;
            orderCompanyId = order.getCompanyId();
            orderNumber = order.getOrderNo();
        } else if ("errand".equals(orderType)) {
            com.ybkj.daijia.server.errand.Order order = errandService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
            }
            if (order.isBaoxiao()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_BAOXIAO);
            }
            financialOrderType = FinancialRecord.ORDER_TYPE_PAOTUI;
            orderCompanyId = order.getCompanyId();
            orderNumber = order.getOrderNo();
        } else if ("freight".equals(orderType)) {
            com.ybkj.daijia.server.freight.Order order = freightService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
            }
            if (order.isBaoxiao()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_BAOXIAO);
            }
            financialOrderType = FinancialRecord.ORDER_TYPE_FREIGHT;
            orderCompanyId = order.getCompanyId();
            orderNumber = order.getOrderNo();
        } else if ("zhuanxian".equals(orderType)) {
            com.ybkj.daijia.server.zhuanxian.Order order = zhuanxianService.findOne(orderId);
            if (null == order) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
            }
            if (order.isBaoxiao()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_BAOXIAO);
            }
            financialOrderType = FinancialRecord.ORDER_TYPE_ZHUANXIAN;
            orderCompanyId = order.getCompanyId();
            orderNumber = order.getOrderNo();
        }

        try {

            Long driverCompanyId = driver.getCompanyId();

            financialRecordService
                .baoxiao(driverCompanyId, orderCompanyId, orderId, financialOrderType, money,
                    orderNumber, driver.getRealname(), memo);

            return ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 driver baoxiao error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }

    /**
     * 查询转单服务人员
     * @return
     */
    @RequestMapping(value = "queryZhuandanEmploys", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport queryZhuandanEmploys(
        String employToken, Long orderId) {

        logger.debug("recv employToken:{},orderId:{}", employToken, orderId);

        if (StringUtils.isBlank(employToken) || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);

        if (null == driverLogin) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
        }

        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
        }

        Driver driver = driverService.findOne(driverLogin.getDriverId());

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }
        if (order.getDriverId() == null || !order.getDriverId().equals(driver.getId())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_EMPLOY_OWNER_ERROR);
        }
        if (!order.getStatus().equals(Order.ORDER_STATUS_YIPAIDAN) && !order.getStatus()
            .equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        try {

            Page<Driver> pageDrivers = driverService
                .queryZhuandanEmploys(driver.getCompanyId(), driver.getId(), null, null);

            List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

            if (pageDrivers.getTotalElements() > 0) {

                List<Driver> content = new ArrayList<Driver>(pageDrivers.getContent());

                for (Driver d : content) {
                    double distance = Distance
                        .doubleVal(d.getLatitude(), d.getLongitude(), driver.getLatitude(),
                            driver.getLongitude());
                    d.setDistance(distance);
                }

                Collections.sort(content, new Comparator<Driver>() {
                    public int compare(Driver arg0, Driver arg1) {
                        return arg0.getDistance().compareTo(arg1.getDistance());
                    }
                });

                Setting setting = settingUtils.get();
                for (Driver d : content) {
                    double distance = Distance
                        .doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                            d.getLatitude(), d.getLongitude());

                    DecimalFormat df = new DecimalFormat("#.00");
                    if (distance >= 1) {
                        d.setDistanceStr(df.format(distance) + "公里");
                    } else {
                        d.setDistanceStr((long) (distance * 1000) + "米");
                    }

                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("driverId", d.getId());
                    map.put("driverName", d.getName());
                    map.put("driverAge", d.getage());
                    map.put("driverJialing", d.getjialing());
                    map.put("driverHead", setting.getWebUrl() + "/upload/driver/" + d.getPhoto());
                    map.put("driverDistance", d.getDistanceStr());
                    map.put("driverMeter", d.getDistance() * 1000);
                    if (d.getStatus().equals(Driver.DRIVER_ONLINE)) {
                        map.put("driverStatus", 0);
                    } else {
                        map.put("driverStatus", 1);
                    }
                    map.put("driverLng", d.getLongitude());
                    map.put("driverLat", d.getLatitude());
                    map.put("workCar", d.isWorkCar());
                    mapList.add(map);

                }
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);
            instance.setData(mapList);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 queryZhuandanEmploys error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }


    }

    /**
     * 工作车转单
     * @param driverId
     * @param orderId
     * @param appKey
     * @param token
     * @param timestamp
     * @return
     */
    @RequestMapping(value = "zhuandan", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport zhuandan(Long employId, Long orderId) {

        logger.debug("recv employId:{},orderId:{}", employId, orderId);

        if (null == employId || null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Driver driver = driverService.findOne(employId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        if (driver.getIsFreeze()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_IS_FREEZE_ERROR);
        }

        if (!driver.getStatus().equals(Driver.DRIVER_ONLINE)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_STATUS_ERROR);
        }

        if (!driver.getDriverJobType().toString()
            .contains(Driver.DriverJobType.daijia.toString())) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_IS_DAIJIA_ERROR);
        }

        Order order = orderService.findOne(orderId);
        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_YIPAIDAN) && !order.getStatus()
            .equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (null == order.getDriverId()) {
            return ResultTransport.getErrorBy(ErrorConstant.ORDER_HAS_BEEN_REVOKE);
        }

        Driver oldDriver = driverService.findOne(order.getDriverId());

        try {

            orderService.zhuandanV4(order, driver, oldDriver);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstant.SUCCESS);

            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("api v4 zhuandanV4 error: {}", e);
            return ResultTransport.getErrorBy(ErrorConstant.SERVER_ERROR);
        }

    }


}

